<template>
  <view class="counter">
    <view class="reduce btn" @click="reduce" :class="{ disable: val <= 0 }"
      >-</view
    >
    <view class="count">{{ val }}</view>
    <view class="add btn" @click="add" :class="{ disable: max && val >= max }"
      >+</view
    >
  </view>
</template>
<script>
export default {
  name: "c-counter",
};
</script>
<script setup lang="ts">
import {
  defineProps,
  inject,
  computed,
  getCurrentInstance,
  unref,
  toRefs,
  reactive,
} from "vue";
const { proxy } = getCurrentInstance() as any;
const props = defineProps({
  modelValue: {
    type: Number,
    default: 1,
  },
  max: {
    type: Number,
  },
});
const state = reactive({
  oldValue: 0,
});

const val = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    proxy.$emit("input", val);
    proxy.$emit("change", val);
  },
});

const reduce = () => {
  if (props.modelValue <= 0) return;
  state.oldValue = props.modelValue;
  val.value -= 1;
};
const add = () => {
  if (props.max && props.modelValue >= props.max) return;
  state.oldValue = props.modelValue;
  val.value += 1;
};
</script>

<style lang="less" scoped>
.counter {
  display: flex;
  align-items: center;

  .disable {
    color: #bbbbbb;
    border: 2rpx solid #bbbbbb !important;
  }

  .count {
    width: 58rpx;
    height: 48rpx;
    background: #f5f5f5;
    border-radius: 8rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 26rpx;
    font-weight: 500;
    margin: 0 15rpx;
  }

  .reduce {
    margin-top: -2rpx;
  }

  .add {
    position: relative;
    margin-top: -2rpx;
  }

  .btn {
    width: 46rpx;
    height: 32rpx;
    border-radius: 16rpx;
    border: 1rpx solid #333333;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>